<template>
	<div class="grades">
		<div class="grades-main">
			<div class="grades-left">
				<el-card style="margin-bottom: 10px; height: 69px">
					<div class="card-header">
						<span>项目类型</span>
					</div>
				</el-card>
				<el-card class="table-box">
					<div style="margin-bottom: 15px">
						<el-button @click="addClassfly.isModelShow = true" :icon="CirclePlus" type="primary">添加类型</el-button>
					</div>
					<el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border default-expand-all>
						<el-table-column prop="name" align="center" label="类型名称" />
						<el-table-column prop="state" align="center" label="状态">
							<template #default="scope">
								<span :class="scope.row.state ? 'erth' : 'noerth'"></span>{{ scope.row.state ? "启用" : "禁用" }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="操作">
							<template #default="scope">
								<el-space wrap>
									<el-tag @click="handleDelete(scope.row.id)" style="cursor: pointer" type="danger"> 删除 </el-tag>
									<el-tag
										@click="handleForbid(scope.row.id, scope.row.state)"
										style="cursor: pointer"
										:type="scope.row.state ? 'warning' : 'success'"
									>
										{{ scope.row.state ? "禁用" : "启用" }}
									</el-tag>
								</el-space>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</div>
			<div class="grades-right">
				<div class="table-box">
					<proTable
						ref="proTableRef"
						:columns="columns"
						:toolButton="true"
						:requestApi="api.GetProjectInfoPageDtoApi"
						:initParam="initParam"
						:dataCallback="dataCallback"
					>
						<template #tableHeader>
							<el-button
								type="primary"
								@click="
									() => {
										addProject.isModelShow = true;
										addProject.type = 1;
									}
								"
								:icon="CirclePlus"
								>新增项目</el-button
							>
						</template>
						<template #operation="scope">
							<el-space wrap>
								<el-tag @click="handleEdit(scope.row)" style="cursor: pointer"> 编辑 </el-tag>
								<el-tag
									@click="handleForbidProject(scope.row.id, scope.row.state)"
									style="cursor: pointer"
									:type="scope.row.state ? 'warning' : 'success'"
								>
									{{ scope.row.state ? "禁用" : "启用" }}
								</el-tag>
							</el-space>
						</template>
					</proTable>
				</div>
			</div>
		</div>
		<!-- 新建项目 -->
		<el-dialog
			v-model="addProject.isModelShow"
			@closed="addProject.handleClose(formRef)"
			:title="addProject.type == 1 ? '新建项目' : '编辑项目'"
			width="30%"
		>
			<el-form :model="addProject.projectFrom" :rules="projectRules" ref="formRef">
				<el-form-item label="所属分类：" prop="TypeId">
					<el-select v-model="addProject.projectFrom.TypeId" placeholder="分类名称">
						<el-option v-for="item in addProject.classflylist" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="项目名称：" prop="ProjectName">
					<el-input v-model="addProject.projectFrom.ProjectName" />
				</el-form-item>
				<el-form-item label="状态：" prop="State">
					<el-radio-group v-model="addProject.projectFrom.State">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addProject.handleClose(formRef)">取消</el-button>
					<el-button type="primary" @click="addProject.handleSubmit(formRef)"> 保存 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 新建分类 -->
		<el-dialog width="30%" @close="addClassfly.handleClose(ClassFormRef)" v-model="addClassfly.isModelShow" title="新建分类">
			<el-form :model="addClassfly.projectFrom" :rules="rules" ref="ClassFormRef">
				<el-form-item label="分类名称：" prop="Name">
					<el-input v-model="addClassfly.projectFrom.Name" />
				</el-form-item>
				<el-form-item label="分类级别：" prop="ParentId">
					<el-cascader
						v-model="addClassfly.projectFrom.ParentId"
						:options="addClassfly.classflylist"
						:props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
					/>
				</el-form-item>
				<el-form-item label="状态：" prop="State">
					<el-radio-group v-model="addClassfly.projectFrom.State">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addClassfly.handleClose(ClassFormRef)">取消</el-button>
					<el-button type="primary" @click="addClassfly.handleSubmit(ClassFormRef)"> 保存 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="tsx" setup>
import { reactive, ref, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";
import api from "@/api/modules/project";
import { dateFormat } from "@/utils/util";
import { ColumnProps } from "@/components/ProTable/interface";
import proTable from "@/components/ProTable/index.vue";
import { GlobalStore } from "@/stores";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// const router = useRouter();
const globalStore = GlobalStore();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	Order: "",
	Sort: ""
});
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};
// 表格配置项
const columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{ prop: "name", label: "项目名称" },
		{ prop: "projectTypeName", label: "项目类型" },
		{
			prop: "state",
			label: "状态",
			enum: [
				{
					label: "全部",
					value: -1
				},
				{
					label: "禁用",
					value: 0
				},
				{
					label: "启用",
					value: 1
				}
			],
			search: { el: "select", props: { filterable: true }, defaultValue: -1 },
			fieldNames: { label: "label", value: "value" },
			render: (scope: { row: any }) => {
				return <> {<el-tag type={scope.row.state ? "success" : "danger"}>{scope.row.state ? "启用" : "禁用"}</el-tag>} </>;
			}
		},
		{
			prop: "createTime",
			label: "添加时间",
			render: (scope: { row: any }) => {
				return <> {dateFormat(scope.row.createTime)} </>;
			}
		},
		{
			prop: "keyWord",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入项目名称" } }
		},
		{ prop: "operation", label: "操作", width: 200, fixed: "right" }
	];
	return data;
});

const formRef = ref<FormInstance>(); //添加/编辑项目模态框表单
const ClassFormRef = ref<FormInstance>(); //添加分类模态框表单
interface Mapdata {
	id: string;
	state: boolean | number;
	name: string;
	parentId: string | null;
	children?: Array<Mapdata>;
}
interface ProjectTtem {
	createTime: string;
	id: string;
	name: string;
	projectTypeId: string;
	projectTypeName: string | null;
	state: number;
}
const tableData = ref<Array<Mapdata>>([]); //分类表格
const gettableDataApi = async () => {
	//获取下拉框数据
	let res = await api.GetAllProjectTypeApi();
	let { data } = res.result as any;
	tableData.value = tranListToTreeData(data);
	addClassfly.classflylist = [
		{
			id: "",
			state: 0,
			name: "无上级分类",
			parentId: null
		},
		...tableData.value
	];
	addProject.classflylist = [...data];
};
const tranListToTreeData = (list: Array<Mapdata>) => {
	//处理扁平数据，转树形
	let treeList: Array<Mapdata> = [];
	let map: any = {};
	list.forEach(item => {
		item.children = [];
		map[item.id] = item;
	});
	list.forEach(item => {
		const res = map[item.parentId as string];
		if (res) {
			res.children.push(item);
		} else {
			treeList.push(item);
		}
	});
	return treeList;
};
gettableDataApi();

const handleEdit = (res: ProjectTtem) => {
	//修改项目
	addProject.isModelShow = true;
	addProject.type = 2;
	let { name, projectTypeId, state, id } = res;
	addProject.id = id;
	addProject.projectFrom = {
		TypeId: projectTypeId, //项目类型标识
		ProjectName: name, //项目名称
		State: state, //状态，0：禁用，1：启用
		CreateId: globalStore.userInfo.id
	};
};
const handleForbidProject = (id: string, bool: any) => {
	//禁用项目
	ElMessageBox.confirm(`确认要${bool ? "禁用" : "启用"}此分类吗？`, {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
		type: "warning"
	}).then(async () => {
		let { result } = await api.UpdateStateApi({
			Id: id, //标识
			State: bool == 0 ? 1 : 0,
			UpdateUserId: globalStore.userInfo.id
			// UpdateUserId:userStore.userInfo.id
		});
		if (result.code != 200) {
			ElMessage({
				type: "error",
				message: `操作失败！`
			});
			return;
		}
		ElMessage({
			type: "success",
			message: `${bool ? "禁用" : "启用"}成功！`
		});
		proTableRef.value.getTableList();
	});
};

const addProject = reactive({
	isModelShow: false, //控制模态框显示隐藏
	type: 1, //鉴别是新增还是编辑
	classflylist: [] as Array<Mapdata>, //分类选项
	id: "", //修改项目id
	projectFrom: {
		TypeId: "", //项目类型标识
		ProjectName: "", //项目名称
		State: 1, //状态，0：禁用，1：启用
		CreateId: globalStore.userInfo.id
	}, //表单信息
	handleSubmit: (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.validate(async (valid: boolean) => {
			if (valid) {
				if (addProject.type == 2) {
					let { TypeId, ProjectName, State, CreateId } = addProject.projectFrom;
					await api.UpdateProjectApi({
						Id: addProject.id,
						TypeId,
						ProjectName,
						State,
						UpdateUserId: CreateId
					});
					ElMessage({
						type: "success",
						message: `修改成功！`
					});
					addProject.isModelShow = false;
					proTableRef.value.getTableList();
					addProject.projectFrom = {
						TypeId: "", //项目类型标识
						ProjectName: "", //项目名称
						State: 1, //状态，0：禁用，1：启用
						CreateId: globalStore.userInfo.id
					};
					return;
				}
				await api.AddProjectInfoApi(addProject.projectFrom);
				ElMessage({
					type: "success",
					message: `添加成功！`
				});
				addProject.isModelShow = false;
				proTableRef.value.getTableList();
			}
		});
	},
	handleClose: (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		addProject.isModelShow = false;
		addProject.projectFrom = {
			TypeId: "", //项目类型标识
			ProjectName: "", //项目名称
			State: 1, //状态，0：禁用，1：启用
			CreateId: globalStore.userInfo.id
		};
		formEl.resetFields();
	}
});
//添加分类
const addClassfly = reactive({
	isModelShow: false, //控制模态框显示隐藏
	classflylist: [] as Array<Mapdata>, //分类选项
	projectFrom: {
		ParentId: [""] as any,
		Name: "",
		State: 1,
		CreateId: globalStore.userInfo.id
	}, //表单信息
	handleSubmit: (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.validate(async valid => {
			if (!valid) return;
			addClassfly.projectFrom.ParentId = addClassfly.projectFrom.ParentId[0];
			await api.AddProjectTypeApi(addClassfly.projectFrom);
			addClassfly.isModelShow = false;
			gettableDataApi();
		});
	},
	handleClose: (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		addClassfly.isModelShow = false;
		addClassfly.projectFrom = {
			ParentId: [""] as any,
			Name: "",
			State: 1,
			CreateId: globalStore.userInfo.id
		};
	}
});
const handleDelete = (id: string) => {
	//添加分类
	ElMessageBox.confirm("再次确认是否要删除此分类", {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
		type: "warning"
	}).then(async () => {
		let { result } = await api.UpdateDeleteStateApi({
			Id: id, //标识
			DeleteUserId: globalStore.userInfo.id //删除人标识
		});
		if (result.code != 200) {
			ElMessage({
				type: "error",
				message: "操作失败！"
			});
		}

		ElMessage({
			type: "success",
			message: "成功删除分类！"
		});
		gettableDataApi();
	});
};
const handleForbid = (id: string, bool: boolean) => {
	//禁用分类
	ElMessageBox.confirm(`确认要${bool ? "禁用" : "启用"}此分类吗？`, {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
		type: "warning"
	}).then(async () => {
		let { result } = await api.UpdateTypeStateApi({
			Id: id,
			State: !bool,
			UpdateUserId: globalStore.userInfo.id
		});
		if (result.code != 200) {
			ElMessage({
				type: "info",
				message: "操作失败！"
			});
			return;
		}
		ElMessage({
			type: "success",
			message: `${bool ? "禁用" : "启用"}成功！`
		});
		gettableDataApi();
	});
};
const rules = reactive<FormRules>({
	ParentId: [{ required: true, message: "分类为必选", trigger: "change" }],
	Name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
	State: [{ required: true, message: "状态是必填项", trigger: "change" }]
});
const projectRules = reactive<FormRules>({
	TypeId: [{ required: true, message: "分类为必选", trigger: "change" }],
	ProjectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
	State: [{ required: true, message: "状态是必填项", trigger: "change" }]
});
</script>

<style lang="scss" scoped>
.box-card {
	margin: none;
}

.erth {
	display: inline-block;
	width: 10px;
	height: 10px;
	border-radius: 50%;
	background-color: #67c23a;
	margin-right: 5px;
}

.noerth {
	display: inline-block;
	width: 10px;
	height: 10px;
	border-radius: 50%;
	background-color: #f56c6c;
	margin-right: 5px;
}

.tableBox {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.card-header {
	display: flex;
	justify-content: space-between;
}

.grades {
	width: auto;
	.grades-main {
		display: flex !important;
		justify-content: space-between;
		min-height: 100vh;

		.grades-left {
			width: 40%;
			height: 100%;
			margin-right: 30px;
		}

		.grades-right {
			width: 55%;
			height: 100%;
		}
	}
}
</style>
